#!/bin/bash

# Search all git repositories under specified directory, and execute git command for each one.
# Usage: git-each-repo [-d <base-directory>] <git-sub-command>
# Example:
# 	pull all repos: git-each-repo -d /directory/contains/many/repos pull

function showUsage {
	echo "Usage: `basename $0` [-d <base-directory>] <git-sub-command>" >&2;
}

[ $# -eq 0 ] && showUsage && exit 1;

while [ $# -gt 0 ]; do
	if [ "$1" = "-d" ]; then
		shift;
		[ $# -eq 0 ] && showUsage && exit 1;
		base_dir="$1";
		shift;
	elif [ "${1:0:2}" = "-d" ]; then
		base_dir="${1:2}";
		shift;
	else
		command="$command $1";
		shift;
	fi
done;

[ -z "$command" ] && showUsage && exit 1;

[ -z "$base_dir" ] && base_dir=".";


#################################################

function isGitRootDir {
	local checkDir="$1";
	pushd "$checkDir" > /dev/null && {
		local gitDir=$(git rev-parse --git-dir 2> /dev/null);
		[ $? -eq 0 -a \( "$gitDir" == '.' -o "$gitDir" == '.git' \) ];
		local result=$?;
		popd > /dev/null;
		return $result;
	};

}

function walkSubDirs {
	local dir="$1";
	if isGitRootDir "$dir"; then
		pushd "$dir" > /dev/null && {
			echo -e '\e[1mProcessing "'$dir'" ...\e[0m';
			git $command;
			echo;
			popd > /dev/null;
		}
	else
		local subdir;
		find "$dir" -mindepth 1 -maxdepth 1 -type d -print0 2>/dev/null | while read -d $'\0' subdir; do
			walkSubDirs "$subdir";
		done;
	fi;
}


walkSubDirs "$base_dir";
